import React, { useState } from 'react';
import DebounceSelect from './DebounceSelect';
import companyApi from '../../api/companyApi';

interface CompanyValue {
  label: string;
  value: string;
  key?: string;
};

type CompanySelectProps = {
  selectId?: string | undefined;
  value?: CompanyValue[] | null | undefined;
  style?: React.CSSProperties;
  onChange?: (value: CompanyValue[] | null | undefined) => void;
};

async function fetchCompanyList(keyword: string): Promise<CompanyValue[]> {
  const res: any = await companyApi.query(keyword, '', '', '', 0, 100);
  const list: any[] = res.data?.list || [];
  return list.map((record: any) => ({
    value: record.company.id,
    label: `${record.company.name} （${record.city.parent.name} / ${record.city.city.name}）`
  }));
};

const CompanySelect: React.FC<CompanySelectProps> = ({ selectId, value, style, onChange, ...props }) => {
  const currentSelectedValue = (value && value.length) ? value[0].value : undefined;
  const [selectedValue, setSelectedValue] = useState<string | null | undefined>(undefined);
  const triggerChange = (changedValue: CompanyValue[] | null | undefined) => {
    onChange?.(changedValue);
  };
  return (
    <DebounceSelect
      id={selectId}
      selectedValue={selectedValue === undefined ? currentSelectedValue : selectedValue}
      placeholder="选择公司"
      fetchOptions={fetchCompanyList}
      onChange={(newValue) => {
        const value = newValue as CompanyValue[];
        setSelectedValue(value?.length ? value[0].value : null);
        triggerChange(value);
      }}
      style={style}
    />
  );
};

export default CompanySelect;
